package feishu

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
)

// 飞书机器人通知

type Robot struct {
	Webhook string
}

func NewRobot(webhook string) *Robot {
	return &Robot{
		Webhook: webhook,
	}
}

// SendMessage 发送具体消息
func (r *Robot) SendMessage(msgType, Content string) error {
	// 默认是 text
	if msgType == "" {
		msgType = "text"
	}
	reqBody := make(map[string]interface{})
	reqBody["content"] = map[string]string{"text": Content}
	reqBody["msg_type"] = msgType
	bodyByte, _ := json.Marshal(reqBody)
	client := &http.Client{Timeout: 5 * time.Second}
	req, err := http.NewRequest("POST", r.Webhook, strings.NewReader(string(bodyByte)))

	if err != nil {
		return err
	}

	res, err := client.Do(req)
	if err != nil {
		return err
	}
	defer res.Body.Close()
	_, err = ioutil.ReadAll(res.Body)
	if err != nil {
		fmt.Println(err)
		return err
	}
	return err
}
